home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: const member functions
- Date: 08 Apr 1996 15:40:46 +0200
- Organization: Fachbereich Informatik, TH Darmstadt
- Sender: enno@kitz.inferenzsysteme.informatik.th-darmstadt.de
- Message-ID: <ltk9zqal5t.fsf@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <316588E6.7D61@geoplex.com>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: "Jay B. Perry"'s message of Fri, 05 Apr 1996 12:56:06 -0800
- X-Newsreader: Gnus v5.1
-
- In article <316588E6.7D61@geoplex.com> "Jay B. Perry" <jay@geoplex.com> writes:
-
- The attached code doesn't compile, complaining about the non-const
- object's attempt to use a non-const private method (even though a
- const public method with the same name is available).
-
- After leafing through a couple of references I have on C++, I have
- come to the conclusion that the attached C++ code should be
- compilable.
-
- Could someone explain to me why this code doesn't work? I have
- tried compiling it using VC++4.1, SunSoft CC SC3.0.1, g++ 2.7.x
- (I am not sure what the current version is, but I know that the
- most current version was used).
-
- My theory is that it is bagging it because it can't differentiate
- between the int& and the int. But, I also had hoped that in the
- context of the call, it should be able to realize that it doesn't
- have access to the private method, so let's see if there is a public
- method that can be used.
-
- As far as options, I just attempted to produce an executable:
-
- g++ -o file file.cc (using g++ as an example)
-
- //
- // Code starts here
- //
- #include <stdlib.h>
- #include <iostream.h>
-
- class X
- {
- public: // Public methods
- X( ) : _value( 0 ) { }
- X( int value ) : _value( value ) { }
-
- // Public accessor, should be available to all
- // X objects.
- int value( ) const { return _value; }
-
- private: // Private methods
- // Private accessor, should only be available to
- // non-const X objects
- int& value( ) { return _value; }
-
- private: // Private data members
- int _value;
- };
-
- main( )
- {
- X t1( 1 );
- const X t2( 2 );
-
- // The following line results in an error for several
- // compilers, all complaining about an attempt to use
- // the private X::value method!
- cout << t1.value() << endl;
-
- // This line
- cout << t2.value() << endl;
- }
-
- 't1' is declared as non-const object of class 'X', both versions of
- 'X::value' are visible and access-control takes place after an
- appropriate function is selected.
- Thus 't1.value()' tries to call the non-const 'X::value' which results
- in an error.
-
- Enno
-
-